<template>
  <div class="editor-html">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      :style="{ height: height + 'px', 'overflow-y': 'hidden' }"
      :model-value="modelValue"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
const props = defineProps({
  height: {
    type: [String, Number],
    default: 500,
  },
  modelValue: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["update:modelValue"]);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 编辑器模式，默认为 'default'，可选 'simple' 或 'read'
const mode = ref("default");
//配置
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  excludeKeys: ["uploadVideo"],
  MENU_CONF: {
    maxFilesSize: 10 * 1024 * 1024, // 限制上传文件大小为 10MB
    sever: "/api/file/uploadFile", // 上传文件的服务器地址
    fileName: "file", // 上传文件的字段名
    comInsert(responseData, insertFn) {
      //正常请求
      if (responseData.code == 200) {
        insertFn(
          proxy.globalInfo.imageUrl + responseData.data.fileName,
          "",
          ""
        );
        return;
      } else if (responseData.code == 500) {
        //登录超时
        store.commit("showLogin", true);
        store.commit("updateLoginUserInfo", null);
        return;
      }
      proxy.Message(responseData.info);
    },
  },
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (editor) => {
  emit("update:modelValue", editor.getHtml());
};
</script>

<style lang="scss" scoped>
.editor-html {
  border: 1px solid #ddd;
  width: 100%;
}
</style>
